const Service = require('egg').Service;
const jwt = require('jsonwebtoken')

class UserService extends Service {
  async login() {
    const { phone, password, nickname } = this.ctx.request.body;
    // egg-validate
    const data = await this.app.mysql.query(`select * from users where phone=? and password=?`, [phone, this.ctx.helper.getPassword(password)]);
    const token = jwt.sign({ ...data[0] }, this.app.config.keys, { expiresIn: "24h" })
    // jwt.verfiy()
    if (data.length) {
      return {
        code: 0, msg: '登陆成功', token
      }
    } else {
      const data = await this.app.mysql.query(`
      insert into users (phone, password, nickname) values (?,?,?)`,
        [phone, this.ctx.helper.getPassword(password), nickname])
      if (data.insertId) {
        return { code: 0, msg: '注册成功', data: data.insertId }
      } else {
        return { code: -1, msg: '注册失败' }
      }
    }
  }
}

module.exports = UserService